//
//  SaApiManager.m
//  saas
//
//  Created by fangyibao on 2019/9/9.
//  Copyright © 2019 fangmao. All rights reserved.
//

#import "SaApiManager.h"
#import "AFNetworking.h"
#import "SaHttpRequest.h"
#import "SaViewControllerUtils.h"


const NSInteger Sa_Code_Error = 10030008;
const NSInteger Sa_Code_Invalid = 10030007;
const NSInteger Sa_Token_Invalid = 401;
const NSInteger Sa_Token_failure = 10010004;
const NSInteger Sa_Request_Success = 200;
const NSInteger Sa_Server_Error = 1;
const NSInteger Sa_ServerSite_Error = 2;


@interface SaApiManager()
@property (strong, nonatomic) AFHTTPSessionManager *manager;
@property (strong, nonatomic) NSMutableDictionary<NSNumber *, NSURLSessionTask *> *dispathTable;

@property (assign, nonatomic) CGFloat totalTaskCount;
@property (assign, nonatomic) CGFloat errorTaskCount;
@property (nonatomic, strong) SaHttpRequest *request;
@end
//static dispatch_semaphore_t lock;
@implementation SaApiManager
-(instancetype)init{
    if (self = [super init]) {
        if (![self conformsToProtocol:@protocol(SaApiManagerProtocol)]){
            NSException *ecp = [NSException exceptionWithName:@"reason" reason:@"实例化ApiManager必须遵守SaApiManagerProtocol" userInfo:nil];
            @throw ecp;
        }
        else self.child = (id<SaApiManagerProtocol>)self;

    }
    return self;
}

/* 单个网络请求时   在内部添加SaProgressHUD */
- (NSURLSessionDataTask *)dataTaskWithParam:(id)param completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler{
    NSMutableURLRequest *request = [self.request generateRequestWithUrlPath:self.child.api useHttps:NO method:self.child.method params:param];
    __block NSNumber *taskIdentifier;
    
    NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [self.dispathTable removeObjectForKey:taskIdentifier];

        if ([responseObject[@"code"] intValue] == Sa_Token_Invalid || [responseObject[@"code"] intValue] == Sa_Token_failure) {
            return;
        }
        if ([responseObject[@"code"] intValue] == Sa_ServerSite_Error) {
            completionHandler(response, nil, nil);
            return;
        }
        if([responseObject[@"code"] intValue] != Sa_Request_Success){
            completionHandler(response, nil, nil);
            return;
        }
        !completionHandler ?: completionHandler(response, responseObject, error);
    }];
    taskIdentifier = @(task.taskIdentifier);
    return task;
}


/* 多个网络请求时   在外面添加SaProgressHUD */
- (NSURLSessionDataTask *)NoSaProgressHUDTaskWithParam:(id)param completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler{
    NSMutableURLRequest *request = [self.request generateRequestWithUrlPath:self.child.api useHttps:NO method:self.child.method params:param];
    [request setValue:@"1" forHTTPHeaderField:@"Tenant-Id"]; // 请求头
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [request setValue:[defaults valueForKey:@"accessToken"] forHTTPHeaderField:@"Authorization"];
    
    __block NSNumber *taskIdentifier;
    
    NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSLog(@" url: %@ *********\n param:%@ ===== %@",self.child.api,param,responseObject);
        
        
        
        [self.dispathTable removeObjectForKey:taskIdentifier];

        if ([responseObject[@"code"] intValue] == Sa_Token_Invalid || [responseObject[@"code"] intValue] == Sa_Token_failure) {
            [SaViewControllerUtils needLogin];
            return;
        }
        if ([responseObject[@"code"] intValue] == Sa_ServerSite_Error) {

            completionHandler(response, nil, nil);
            return;
        }
        if([responseObject[@"code"] intValue] != Sa_Request_Success){
//            [SaProgressHUD showText:responseObject[@"errorMessage"]];
            completionHandler(response, responseObject, nil);
            return;
        }
        !completionHandler ?: completionHandler(response, responseObject, error);
    }];
    taskIdentifier = @(task.taskIdentifier);
    return task;
}



- (NSURLSessionDataTask *)uploadImageWithParam:(id)param sourceImg:(UIImage *)img completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler{
    NSMutableURLRequest *req = [self.request generateUploadRequestWithUrl:self.child.api method:@"POST" souceImg:img params:param];
    
    [req setValue:@"1" forHTTPHeaderField:@"Tenant-Id"]; // 请求头
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [req setValue:[defaults valueForKey:@"accessToken"] forHTTPHeaderField:@"Authorization"];
    
    
    [SaProgressHUD showSVP:@"图片上传中请稍后..."];
    __block NSNumber *taskIdentifier;
    NSURLSessionDataTask *task = [self.manager uploadTaskWithStreamedRequest:req progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
        [self.dispathTable removeObjectForKey:taskIdentifier];
//        dispatch_semaphore_signal(lock);
        [SaProgressHUD dissSVP];
        if ([responseObject[@"code"] intValue] == Sa_Token_Invalid || [responseObject[@"code"] intValue] == Sa_Token_failure) {
            [SaViewControllerUtils needLogin];
            return;
        }
        if([responseObject[@"code"] intValue] != Sa_Request_Success){
            [SaProgressHUD showText:responseObject[@"errorMessage"]];
            completionHandler(response, nil, error);
            return;
        }
        !completionHandler ?: completionHandler(response, responseObject, error);
    }];
    taskIdentifier = @(task.taskIdentifier);
    [task resume];
    return task;
}

- (NSURLSessionDataTask *)uploadImagesWithParam:(id)param imgs:(NSArray *)imgs completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler{
    NSMutableURLRequest *req = [self.request generateUploadRequestWithUrl:self.child.api method:@"POST" imgs:imgs params:param];
   
    [req setValue:@"1" forHTTPHeaderField:@"Tenant-Id"]; // 请求头
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [req setValue:[defaults valueForKey:@"accessToken"] forHTTPHeaderField:@"Authorization"];
    
    [SaProgressHUD showSVP:@"图片上传中请稍后..."];
    __block NSNumber *taskIdentifier;
    NSURLSessionDataTask *task = [self.manager uploadTaskWithStreamedRequest:req progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
        [self.dispathTable removeObjectForKey:taskIdentifier];
//        dispatch_semaphore_signal(lock);
        [SaProgressHUD dissSVP];
        if ([responseObject[@"code"] intValue] == Sa_Token_Invalid || [responseObject[@"code"] intValue] == Sa_Token_failure) {
            [SaViewControllerUtils needLogin];
            return;
        }
        if([responseObject[@"code"] intValue] != Sa_Request_Success){
            [SaProgressHUD showText:responseObject[@"errorMessage"]];
            completionHandler(response, responseObject, error);
            return;
        }
        !completionHandler ?: completionHandler(response, responseObject, error);
    }];
    taskIdentifier = @(task.taskIdentifier);
    [task resume];
    return task;
}

- (NSNumber *)dispatchTask:(NSURLSessionTask *)task{
    if (task == nil) { return @-1; }
    
//    dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
    [self.dispathTable setObject:task forKey:@(task.taskIdentifier)];
//    dispatch_semaphore_signal(lock);
//    [SaProgressHUD showSVP:@"加载中···"];
    [task resume];
    return @(task.taskIdentifier);
}

- (NSNumber *)noSapRorgress:(NSURLSessionTask *)task{
    if (task == nil) { return @-1; }
    
    [self.dispathTable setObject:task forKey:@(task.taskIdentifier)];
    [task resume];
    return @(task.taskIdentifier);
}


- (NSNumber *)dispatchTaskWithParam:(id)param completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler{
//    if ((NSDictionary *)param[@"SaProgressHUD"]) { // 如果有这个值  则表示一个界面有多个网络请求  则在外部添加SaProgressHUD这个属性
//        return [self dispatchTask:[self dataTaskWithParam:param completionHandler:completionHandler]];
//    }else{
        return [self noSapRorgress:[self NoSaProgressHUDTaskWithParam:param completionHandler:completionHandler]];
//    }
    
}
- (void)cancelAllTask{
    for (NSURLSessionTask *task in self.dispathTable.allValues) {
        [task cancel];
    }
//    dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
    [self.dispathTable removeAllObjects];
//    dispatch_semaphore_signal(lock);
}
- (void)cancelTaskWithTaskIdentifier:(NSNumber *)taskIdentifier{
    [self.dispathTable[taskIdentifier] cancel];
    
//    dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
    [self.dispathTable removeObjectForKey:taskIdentifier];
//    dispatch_semaphore_signal(lock);
}
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.securityPolicy.validatesDomainName = NO;
        _manager.securityPolicy.allowInvalidCertificates = YES;
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    }
    return _manager;
}
- (SaHttpRequest *)request{
    if (!_request) {
        _request = [SaHttpRequest shareRequest];
    }
    return _request;
}
@end
